package com.lh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.entity.table.LeadLeader;
import com.lh.entity.table.ReminderPerson;
import com.lh.entity.table.ResponsiblePerson;
import com.lh.mapper.ReminderPersonMapper;
import com.lh.mapper.ResponsiblePersonMapper;
import com.lh.service.ResponsiblePersonService;
import com.lh.utils.Answer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ResponsiblePersonServiceImpl implements ResponsiblePersonService {
    @Resource
    private ResponsiblePersonMapper responsiblePersonMapper;

    @Resource
    private ReminderPersonMapper reminderPersonMapper;


    @Override
    public Answer<Object> getResponsiblePersonPage(JSONObject reqJson) {
        Integer pageSize = reqJson.getInteger("pageSize"); // 默认10条/页
        Integer pageNum = reqJson.getInteger("pageNum");    // 默认第1页
        String name = reqJson.getString("name");
        String department = reqJson.getString("department");
        if (pageNum < 1) pageNum = 1; // 防止pageNum为0或负数
        Page<ResponsiblePerson> queryPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ResponsiblePerson> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(name)){
            queryWrapper.like(ResponsiblePerson::getName,name);
        }
        if (StringUtils.isNotBlank(department)){
            queryWrapper.like(ResponsiblePerson::getDepartment,department);
        }
        Page<ResponsiblePerson> responsiblePersonPage = responsiblePersonMapper.selectPage(queryPage, queryWrapper);
        return Answer.ok(responsiblePersonPage);
    }

    @Override
    public Answer<Object> getResponsiblePersonList() {
        List<ResponsiblePerson> responsiblePeopleList = responsiblePersonMapper.selectList(new LambdaQueryWrapper<>());
        List<String> esponsiblePeopleNameList = responsiblePeopleList.stream()
                .filter(a -> a.getName() != null && StringUtils.isNotBlank(a.getName()))
                .map(ResponsiblePerson::getName)
                .collect(Collectors.toList());
        return Answer.ok(esponsiblePeopleNameList);
    }

    @Override
    public String[] getDepartmentFromName(String personName) {
        // 1. 入参校验：姓名为空直接返回空数组（避免返回null导致NPE）
        if (StrUtil.isBlank(personName)) {
            return new String[0];
        }
        // 2. 按多种分隔符拆分姓名（支持逗号、斜杠、点、顿号）
        String[] nodeResponsiblePeople = personName.split("[,/.、]");
        // 过滤空字符串（避免拆分后出现空值，如连续分隔符导致的空项）
        List<String> nameList = Arrays.stream(nodeResponsiblePeople)
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .collect(Collectors.toList());

        // 3. 姓名列表为空时返回空数组
        if (nameList.isEmpty()) {
            return new String[0];
        }
        // 4. 批量查询所有姓名对应的部门（使用in条件高效查询）
        LambdaQueryWrapper<ResponsiblePerson> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ResponsiblePerson::getName, nameList);
        List<ResponsiblePerson> persons = responsiblePersonMapper.selectList(queryWrapper);
        // 5. 提取部门并去重（使用LinkedHashSet保留插入顺序，同时去重）
        Set<String> departmentSet = new LinkedHashSet<>();
        for (ResponsiblePerson person : persons) {
            String dept = person.getDepartment();
            if (StrUtil.isNotBlank(dept)) { // 过滤空部门
                departmentSet.add(dept.trim());
            }
        }
        // 6. 转换为数组返回（若需排序可在此处添加排序逻辑）
        return departmentSet.toArray(new String[0]);
    }

    @Override
    public Answer<Object> addResponsiblePerson(ResponsiblePerson responsiblePerson) {
        String name = responsiblePerson.getName();
        ResponsiblePerson responsiblePersons = responsiblePersonMapper.selectOne(new LambdaQueryWrapper<ResponsiblePerson>().eq(ResponsiblePerson::getName, name));
        if (responsiblePersons != null){
            return Answer.ok("责任人姓名已存在");
        }
        ReminderPerson reminderPerson = new ReminderPerson();
        reminderPerson.setPersonName(responsiblePerson.getName());
        reminderPerson.setPhone(responsiblePerson.getPhone());
        reminderPerson.setUnitName(responsiblePerson.getDepartment());
        reminderPersonMapper.insert(reminderPerson);
        responsiblePersonMapper.insert(responsiblePerson);
        return Answer.ok("添加成功");
    }

    @Override
    public Answer<Object> updateResponsiblePerson(ResponsiblePerson responsiblePerson) {
        String name = responsiblePerson.getName();
        ResponsiblePerson responsiblePersons = responsiblePersonMapper.selectOne(new LambdaQueryWrapper<ResponsiblePerson>().eq(ResponsiblePerson::getName, name));
        if (responsiblePersons == null){
            return Answer.ok("责任人姓名不存在，请先添加责任人");
        }
        responsiblePersonMapper.updateById(responsiblePerson);
        return Answer.ok("更新成功");
    }

    @Override
    public Answer<Object> deleteResponsiblePersonById(JSONObject reqJson) {
        Integer id = reqJson.getInteger("id");
        responsiblePersonMapper.deleteById(id);
        return Answer.ok("删除成功");
    }
}
